import express from "express";
import db from "../db/db.js";

const addAssetRecord = express.Router();

const detailData = async (params: any) => {
    return new Promise((resolve, reject) => {
        // Step 1: 查询是否存在指定的 fundName
        let selectSql = `SELECT curAsset, date, principal, firstHoldTime, code FROM asset WHERE fundName = ? ORDER BY date DESC LIMIT 1`;

        db.query(selectSql, [params.name], (err, selectResults) => {
            let sql;
            let data;
            if (err) {
                sql = `INSERT INTO asset SET 
                source = ?,date = ?, fundName = ?, fundType = ?, curAsset = ?`;
                data = [params.source, new Date(params.date), params.name, params.financialType, params.fundNum];
            } else {
                let lastFund = 0;
                let principal = 0;
                let firstHoldTime;
                let code;
                if (selectResults.length > 0) {
                    // Step 2: 如果有记录，获取最新的 curAsset 和 date
                    const latestRecord = selectResults[0];
                    lastFund = latestRecord.curAsset;
                    principal = latestRecord.principal;
                    firstHoldTime = latestRecord.firstHoldTime;
                    code = latestRecord.code;
                }
                // Step 3: 计算 positionGain
                const positionGain = params.fundNum - principal;

                // Step 4: 插入新的记录到 asset 表
                sql = `INSERT INTO asset SET 
                source = ?, date = ?, fundName = ?, fundType = ?, principal = ?, curAsset = ?, lastFund = ?, firstHoldTime = ?, positionGain = ?, code = ?`;
                data = [params.source, new Date(params.date), params.name, params.financialType, principal, params.fundNum, lastFund, firstHoldTime, positionGain, code];
            }

            db.query(sql, data, (insertErr, insertResults) => {
                if (insertErr) {
                    return reject(insertErr);
                }
                resolve(insertResults);
            });
        });
    });
};

addAssetRecord.post("/createAssetRecord", async (req, res) => {
    try {
        const params = req.body;
        const dataRes: any = await detailData(params);
        res.send({
            code: 200,
            message: "修改忽略状态完成 请求成功！",
            result: dataRes,
            // total: dataRes.length,
        });
    } catch (error) {
        console.error("Error fetching file records:", error);
        res.status(500).send({
            code: 1,
            message: "修改忽略状态完成 请求失败！",
            result: null,
        });
    }
});

export default addAssetRecord;
